package com.example.web.tool;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import lombok.extern.slf4j.Slf4j;
/**
 * @since File upload tool class
 * @author HuWang
 *
 */
@Component
@Slf4j
public class FileUtils {

	@Value("${spring.savefile.url}")
	private  String filePaths;
	
    /**
     * 	单文件上传
     * @param multipartFile
     * @param dirParam
     * @return
     */
      public  String oneUpload(MultipartFile multipartFile, String dirParam) {
      	String urlName = multipartFile.getOriginalFilename();
      		//获取文件是否为null
          if (multipartFile == null || multipartFile.isEmpty()) {
              return null;
          }
          String relativePath = "";
          
          File dir = new File(filePaths.toString());
          if (!dir.exists()) {
              dir.mkdirs();
          }
          
          relativePath = filePaths+"/" + urlName;
          try {
              multipartFile.transferTo(new File(relativePath));
          } catch (IOException e) {
              log.error("保存文件失败", e);
              e.printStackTrace();
          }
          String res = "/files/"+ urlName;
          log.info("文件" + urlName + "保存的相对路径" + res);
          return res;
      }
  
      public List<String> manyUpload(List<MultipartFile> multipartFiles) {
    	  List<String> list = new ArrayList<String>();
    	  MultipartFile file = null;
          BufferedOutputStream stream = null;
          for (int i = 0; i < multipartFiles.size(); ++i) {
              file = multipartFiles.get(i);
              if (!file.isEmpty()) {
                  try {
                      byte[] bytes = file.getBytes();
                      stream = new BufferedOutputStream(new FileOutputStream(
                              new File(filePaths + "/" + file.getOriginalFilename())));//设置文件路径及名字
                      stream.write(bytes);// 写入
                      stream.close();
                  } catch (Exception e) {
                      stream = null;
                  }
              } else {
            	  return null;
              }
              list.add("/files/"+ file.getOriginalFilename());
          }
          return list;
      }
    /**
     * 	文件下载
     * @param filePath
     * @param response
     * @throws IOException
     */
    public static void download(String filePath, HttpServletResponse response) throws IOException {
        File file = new File(filePath);
        String fileName = file.getName().replaceAll(" ", "");
        InputStream fis = null;
        byte[] bytes = null;
        try {
            fis = new BufferedInputStream(new FileInputStream(file));
            bytes = new byte[fis.available()];
            fis.read(bytes);
        } catch (FileNotFoundException e) {
        	log.error("文件流创建失败", e);
            e.printStackTrace();
        } finally {
            fis.close();
        }
        response.reset();
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso8859-1"));
        response.addHeader("Content-Length", String.valueOf(file.length()));
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
    }
}
